<template>
	<Layout showFooter>
		<template #title>确定订单</template>
		<view class="inline-flex fill p30">
			<view class="inline-flex aic jcsb section-box service-detail">
				<image class="service-detail__image" :src="detail.mainImgUrl"></image>
				<view class="inline-flex column jcsb service-detail__info">
					<view class="service-detail__info__intro">
						<view class="ellipsis-line-clamp">
							{{detail.spuName}}
						</view>
					</view>
					<view class="service-detail__info__price">
						<text class="rmb-symbol">¥</text>
						<text class="rmb-number">{{pennyToDollarFormat(detail.priceFee)}}</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 文书模板 -->
		<InfoBlock v-if="serviceType === ServiceType.WritTemplate">
			<InfoBlockItem color="rl">
				<template #label>支付方式</template>
				微信支付
			</InfoBlockItem>

			<InfoBlockItem color="rl">
				<template #label>输入邮箱</template>
				<u-input v-model="formData.email" placeholder="请输入" input-align="right"></u-input>
			</InfoBlockItem>
		</InfoBlock>

		<!-- 代写文书 -->
		<InfoBlock v-else-if="serviceType === ServiceType.GhostwriteWrit">
			<InfoBlockItem color="rl">
				<template #label>服务律师</template>
				平台指派律师
			</InfoBlockItem>

			<InfoBlockItem color="rl">
				<template #label>联系电话</template>
				<u-input v-model="formData.contactPhone" placeholder="请输入" input-align="right"></u-input>
			</InfoBlockItem>

			<InfoBlockItem color="rl">
				<template #label>优惠券</template>
				暂无可用
			</InfoBlockItem>

			<InfoBlockItem color="ll">
				<template #label>联系人</template>
				<u-input v-model="formData.contactName" placeholder="请输入" input-align="right"></u-input>
			</InfoBlockItem>
			<view class="inline-flex fill p20">
				<view class="inline-flex fill form-content">
					<view class="form-content__textarea">
						<u-input :style="{width:'100%'}" height="270" type="textarea" maxlength="500"
							v-model="formData.remark" :custom-style="{width:'100%',backgroundColor:'#F9F9F9'}"
							placeholder="请输入描述需求和遇到问题"></u-input>
					</view>
					<view class="form-content__compute">{{formData.remark.length}}/500</view>
				</view>
			</view>
		</InfoBlock>

		<!-- 法律咨询 -->
		<InfoBlock v-else="serviceType === ServiceType.LegalConsulting">
			<InfoBlockItem color="ll">
				<template #label>联系人</template>
				<u-input v-model="formData.contactName" placeholder="请输入" input-align="right"></u-input>
			</InfoBlockItem>
			<InfoBlockItem color="rl">
				<template #label>联系电话</template>
				<u-input v-model="formData.contactPhone" placeholder="请输入" input-align="right"></u-input>
			</InfoBlockItem>
		</InfoBlock>


		<!-- 代写服务、法律咨询才有阅读服务规范 -->
		<view v-if="serviceType === ServiceType.GhostwriteWrit || serviceType === ServiceType.LegalConsulting"
			class="inline-flex fill p30 aic agreement ">
			<u-checkbox v-model="agreement"></u-checkbox>
			我已阅读并同意<text @click.stop="tapToAgreement">《服务规范》</text>
		</view>

		<u-top-tips ref="tipsRef" :navbarHeight="navbarHeight"></u-top-tips>

		<template #footer>
			<view class="inline-flex fill jcsb p30">
				<view class="inline-flex sdf-left summation">
					<text class="summation__text">合计：</text>
					<view class="rmb">
						<text class="rmb-symbol">￥</text>
						<text class="rmb-price">{{pennyToDollarFormat(detail.priceFee)}}</text>
					</view>
				</view>

				<view class="inline-flex sdf-right">
					<u-button size="submajor" type="primary" @click="tapSubmit">
						<text>
							{{serviceType === ServiceType.WritTemplate ?'支付下载':'立即购买'}}
						</text>
					</u-button>
				</view>
			</view>
		</template>

	</Layout>
	<LoginPopup></LoginPopup>
</template>

<script setup lang="ts">
	import Layout from '@/components/layout/layout.vue';
	import InfoBlock from '@/components/info-block/info-block.vue';
	import InfoBlockItem from '@/components/info-block/info-block-item.vue';
	import { onLoad } from '@dcloudio/uni-app';
	import { ServiceType } from '@/utils/constant';
	import { ref, inject } from 'vue';
	import { getSpuDetail } from '@/apis/service';
	import { pennyToDollarFormat } from '@/utils/format';
	import { isValidateEmail, isEmpty } from '@/utils/util';
	import { useShowTipMessage } from '@/hooks/util';
	import type { BoundingRect } from '@/hooks/bounding-rect';
	import { submitOrder } from '@/apis/trade';
	import { isLogin } from '@/utils/auth';
	import { useAuthStore } from '@/stores';
	import type { AnyObj } from '@/types/global';
	const authStore = useAuthStore();
	const rect = inject<BoundingRect>('boundingRect');
	const navbarHeight = ref<number>(rect.safeArea.topHeight);
	const [tipsRef, showTipMessage] = useShowTipMessage();
	let spuId = '';
	const serviceType = ref<ServiceType>(ServiceType.None)
	const detail = ref<AnyObj>({});
	function loadData() {
		getSpuDetail(spuId).then((result) => {
			if (result.code !== 200) {
				uni.showToast({
					icon: 'none',
					title: result.msg ?? '服务器忙，请稍后再试'
				});
				return;
			}
			detail.value = result.data;
			console.log(result);
			serviceType.value = result.data.categoryParentId;
			// serviceType.value = 1;
		});
	}

	onLoad((option) => {
		option = option as { spuId : string; };
		spuId = option.spuId;
		loadData();
	});

	const agreement = ref(false);

	function tapToAgreement() {
		uni.navigateTo({
			url: '/pages-mine/agreement/agreement?docType=3'
		})
	}

	const formData = ref({
		// appId: '', // 必填，在接口端统一填入
		// openId: '', // 必填，在接口端统一填入
		// wxUserId: '', // 必填，在接口端统一填入
		spuId: '',
		count: 1,
		contactName: '',
		contactPhone: '',
		email: '',
		remark: '',
	})

	function tapSubmit() {
		const data = { ...formData.value, spuId };

		if (serviceType.value === ServiceType.WritTemplate) {
			if (!isValidateEmail(data.email)) {
				showTipMessage('请输入正确的邮箱地址 ', 'error');
				return
			}
		}

		if (serviceType.value === ServiceType.GhostwriteWrit ||
			serviceType.value === ServiceType.LegalConsulting) {
			if (isEmpty(data.contactPhone) || data.contactPhone.length > 11) {
				showTipMessage('请输入联系电话，11个字以内 ', 'error');
				return
			}

			if (isEmpty(data.contactName) || data.contactName.length > 11) {
				showTipMessage('请输入联系人，20个字以内 ', 'error');
				return
			}
		}

		if (serviceType.value === ServiceType.GhostwriteWrit) {
			if (isEmpty(data.remark) || data.remark.length > 500) {
				showTipMessage('请输入需求，500个字以内 ', 'error');
				return
			}
		}
		console.log(agreement.value);
		if ((serviceType.value === ServiceType.GhostwriteWrit ||
			serviceType.value === ServiceType.LegalConsulting) && (!agreement.value)) {
			uni.showToast({
				icon: 'none',
				title: '请阅读并同意服务规范'
			});
			return
		}

		if (!isLogin()) {
			authStore.show();
			uni.showToast({
				icon: 'none',
				title: '请先登录'
			});
			return
		}

		submitOrder(data).then((result) => {
			if (result.code !== 200) {
				uni.showToast({
					icon: 'none',
					title: result.msg ?? '服务器忙请稍后再试'
				});
				return;
			}
			const resultData = result.data as AnyObj;
			let msg = '';
			switch (serviceType.value) {
				case ServiceType.WritTemplate:
					msg = '平台稍后会将模版发送至邮箱，请注意查收';
					break;
				case ServiceType.GhostwriteWrit:
					msg = '等待客服人员联系';
					break;
				case ServiceType.LegalConsulting:
					msg = '平台会安排专业律师为您服务请注意接听电话';
					break;
			}

			const paymentData = {
				...resultData,
				package: resultData.packageValue,
			}

			const storeKey = `payment_${new Date().valueOf()}_`;

			wx.requestPayment({
				...paymentData,
				success: () => {
					uni.navigateTo({
						// url: `/pages-service/pay-success/pay-success?serviceType=${serviceType.value}`
						url: `/pages-other/pay-success/pay-success?msg=${msg}`
					});
				},
				fail: (err : any) => {
					// uni.setStorageSync(`${storeKey}data`, JSON.stringify(paymentData))
					// uni.setStorageSync(`${storeKey}msg`, msg)
					console.log(err);
					uni.showToast({
						icon: 'none',
						title: '取消支付'
					});
					// uni.navigateTo({
					// 	url: `/pages-other/pay-failed/pay-failed?storeKey=${storeKey}`
					// });
				}
			} as any
			);
		});
	}
</script>

<style scope lang="scss">
	.section-box {
		width: 690rpx;
		padding: 24rpx;
		border-radius: 8rpx;
		background: #FFF;
	}

	.service-detail {
		&__image {
			width: 168rpx;
			height: 168rpx;
			flex-shrink: 0;
			border-radius: 20rpx;
		}

		&__info {
			width: 450rpx;
			height: 168rpx;
			padding: 13rpx 0 10rpx 0;

			&__intro {
				color: #000000;
				font-family: "PingFang SC";
				font-size: 30rpx;
				font-style: normal;
				font-weight: 500;
				line-height: normal;
			}

			&__price {

				.rmb-symbol {
					color: #101010;
					text-align: center;
					font-family: "PingFang SC";
					font-size: 24rpx;
					font-style: normal;
					font-weight: 600;
					line-height: normal;
				}

				.rmb-number {
					color: #101010;
					text-align: center;
					font-family: "PingFang SC";
					font-size: 40rpx;
					font-style: normal;
					font-weight: 600;
					line-height: normal;
				}
			}
		}
	}

	.form-content {
		padding: 20rpx 20rpx 50rpx 20rpx;
		background: #F9F9F9;
		border-radius: 12rpx;

		&__textarea {
			display: inline-block;
			width: 100%;
			height: 310rpx;
			overflow-y: auto;
		}

		&__compute {
			position: absolute;
			right: 20rpx;
			bottom: 20rpx;
			color: #929292;
			font-family: "PingFang SC";
			font-size: 24rpx;
			font-style: normal;
			font-weight: 400;
			line-height: normal;
		}
	}

	.agreement {
		color: #929292;
		font-family: "PingFang SC";
		font-size: 28rpx;
		line-height: 28rpx;

		text {
			color: #000000;
		}
	}

	.sdf {
		&-left {
			.rmb {
				&-symbol {
					color: #F65C5C;
					font-family: "PingFang SC";
					font-size: 28rpx;
					font-weight: 500;
				}

				&-price {
					line-height: 52rpx;
					font-size: 52rpx;
					color: #F65C5C;
					font-weight: 600;
				}
			}

			&.summation {
				align-items: flex-end;

				&__text {
					color: #000000;
					font-family: "PingFang SC";
					font-size: 28rpx;
					font-weight: 400;
				}
			}
		}
	}
</style>